package com.liarjo.my_website_api.security.handler;

import cn.hutool.json.JSONUtil;
import com.liarjo.my_website_api.security.SecurityUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class SecurityAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private SecurityUtil securityUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json");
        response.setCharacterEncoding("utf-8");

        response.setStatus(HttpServletResponse.SC_OK);
        String token = securityUtil.getSecurityUser().getToken();
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        response.getWriter().write(JSONUtil.toJsonStr(result));
    }
}
